Your First Program: Hello World!
From now on, we will assume that you have Python installed on your system.
Next, we will write our first Python program.
We will now see how to run a traditional 'Hello World' program in Python. This will teach you how to write, save and run Python programs.
There are two ways of using Python to run your program - using the interactive interpreter prompt or using a source file. We will now see how to use both of these methods.
Using the Interpreter Prompt
Open the terminal in your operating system (as discussed previously in the Installation chapter) or launch IDLE and use the Python shell. If you are on Windows or Raspbian, running the Python shell in IDLE is easiest.
Once you have started Python, you should see >>>
where
you can start typing stuff. This is called the Python interpreter
prompt.
There is a tradition that whenever you learn a new programming language, the first program that you write and run is the 'Hello World' program - all it does is just say 'Hello World' when you run it. As Simon Cozens, the author of the amazing book Beginning Perl, says, it is the "traditional incantation to the programming gods to help you learn the language better."
At the Python interpreter prompt, type:
print("Hello World!")
followed by the [enter]
key. You should see the words
Hello World!
printed to the screen.
Notice that Python gives you the output of the line immediately! What you
just entered is a single Python statement. We use print
to
(unsurprisingly) print any value that you supply to it. Here, we are supplying
the text Hello World!
and this is promptly printed to the screen.
Congratulations! You just executed your first Python program.
Choosing an Editor
We cannot type out our program at the interpreter prompt every time we want to run something – it would take forever - so we have to save them in files. This way we can run our programs any number of times and make edits much quicker and easier.
To create our Python source files, we need an editing software where you can type and save. A good programmer's editor will make your life easier in writing the source files. Hence, the choice of an editor is crucial indeed. You have to choose an editor as you would choose a car you would buy. A good editor will help you write Python programs easily, making your journey more comfortable and helps you reach your destination (achieve your goal) in a much faster and safer way.
One of the very basic requirements is syntax highlighting where all the different parts of your Python program are colorized so that you can see your program and visualize its running.
If you are using Windows, do not use Notepad - it is a bad choice because it does not do syntax highlighting and also importantly it does not support indentation of the text which is very important in our case as we will see later. Good editors will automatically do this.
A few suggestions:
- IDLE – comes bundled with Python. Contains syntax highlighting. Easy to run programs. Probably your best choice at this level for Raspbian and Windows use.
- Notepad++ - a free text editor for Windows
- PyCharm Educational Edition - available on Windows, Mac OS X and GNU/Linux.
- Vim or Emacs - two of the most powerful editors and you will benefit from using them to write your Python programs.
In case you are willing to take the time to learn Vim or Emacs, then I highly recommend that you do learn to use either of them as it will be very useful for you in the long run. However, as I mentioned before, beginners can start with IDLE, Notepad++, or PyCharm and focus the learning on Python rather than the editor at this moment.
Since IDLE comes bundles with Python, I will be using it in all future screen captures and directions.
To reiterate, please choose a proper editor - it can make writing Python programs more fun and easy.
Using a Source File
Now let's get back to programming. Start IDLE and open a new file by
going to File > New File
.
A lovely blank file will display:
The very first thing you need to do is save this file and
give it a location and name that you will remember. For this exercise, we
are going to be name it hello.py.
Go to File > Save As
.
Find a good location for the file. Where should you save the file? To any folder for which you know the location of the folder. If you don't understand what that means, create a new folder and use that location to save and run all your Python programs.
Give it a name of hello.py
and click Save. IMPORTANT:
Always ensure that you give it the file extension of .py
, for
example, foo.py
. IDLE does not automatically add the
extension of .py
. You need to do this yourself! If you
forget, you will not see the fun syntax highlighting which makes editors so
useful.
Now that we have opened a new file, saved it with the name "hello.py" we are now ready to write a program.
Type this:
print("Hello World!")
Save your file.
Now we are going to run the program. There's a few ways to do this. You can…
- Open a terminal window, find the file, and execute it.
- Double click the program to launch the terminal window
- Run it in IDLE.
Since we are already using IDLE, it makes sense to run it using IDLE.
To do this, go to Run > Run Module
or in Windows, hit
F5
. The Python Shell should display and your program should
execute:
If you got the output as shown above, congratulations! - you have successfully run your first Python program. You have successfully crossed the hardest part of learning programming, which is, getting started with your first program!
In case you got an error, please type the above program exactly as
shown above and run the program again. Note that Python is case-sensitive i.e.
print
is not the same as Print
- note the
lowercase p
in the former and the uppercase P
in
the latter. Also, ensure there are no spaces or tabs before the first character
in each line - we will see why this is important later.
How "Hello World!" Works
Code | Output | Notes |
---|---|---|
print("Hello World!") |
Hello World! |
A Python program is composed of statements. In our first
program, we have only one statement. In this statement, we call the
print statement to which we supply the text "Hello
world!". |
You should now be able to write, save and run Python programs at ease.
Now that you are a Python user, let's learn some more Python concepts.
Exercise: Hello World!
Now it is your turn to try out Hello World. Click on the icon below to launch the interactive exercise. There will be many of these through out the text. You should:
- Read the instructions
- Write the code
- Click Run to test the code
- Click Save to save what you have done and return
- Click Submit to submit it to me.
- If the exercise contains a hint, you can click the Hint button to view the hint.
- If the exercise gives you code to start with, you can click the Redo button to revert back to the starting code.
These exercises are also compiled together under Our Classroom.
Formal and Natural languages
Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:
Programming languages are formal languages that have been designed to express computations.
Formal languages tend to have strict syntax rules that govern the structure of statements. For example, in mathematics the statement 3 + 3 = 6 has correct syntax, but 3 + = 3 $ 6 does not. In chemistry H2O is a syntactically correct formula, but 2Zz is not.
Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with 3 += 3 $ 6 is that $ is not a legal token in mathematics (at least as far as I know). Similarly, 2Zz is not legal because there is no element with the abbreviation Zz.
The second type of syntax rule pertains to the way tokens are combined. The equation 3 += 3 is illegal because even though + and = are legal tokens, you can't have one right after the other. Similarly, in a chemical formula the subscript comes after the element name, not before.
This is @ well-structured Engli$h sentence with invalid t*kens in it.
This sentence all valid tokens has, but invalid structure with.
When you read a sentence in English or a statement in a formal language, you have to figure out the structure (although in a natural language you do this subconsciously). This process is called parsing.
Although formal and natural languages have many features in common—tokens, structure, and syntax—there are some differences:
ambiguity: Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.
redundancy: In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.
literalness: Natural languages are full of idiom and metaphor. If I say, "The penny dropped", there is probably no penny and nothing dropping (this idiom means that someone understood something after a period of confusion). Formal languages mean exactly what they say.
Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. The difference between formal and natural language is like the difference between poetry and prose, but more so:
Poetry: Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate.
Prose: The literal meaning of words is more important, and the structure contributes more meaning. Prose is more amenable to analysis than poetry but still often ambiguous.
Programs: The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.
Formal languages are denser than natural languages, so it takes longer to read them. Also, the structure is important, so it is not always best to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language.
Getting Help
If you need quick information about any function or statement in Python, then
you can use the built-in help
functionality. This is very useful
especially when using the interpreter prompt. For example, run
help('print')
- this displays the help for the print
function which is used to display output onto the screen.
Similarly, you can obtain information about almost anything in Python. Use
help()
to learn more about using help
itself!
In case you need to get help for operators like return
, then
you need to put those inside quotes such as help('return')
so
that Python doesn't get confused on what we're trying to do.
Debugging
Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging.
Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed.
There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people (Reeves and Nass, The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places).
Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.
Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.
Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each lesson there is a section, like this one, with suggestions for debugging. I hope they help!
Exercises
It is a good idea to read this book in front of a computer so you can try out the examples as you go.
Exercise 1
Whenever you are experimenting with a new feature, you should try to make mistakes.
For example, in the "Hello, world!" program,
- What happens if you leave out one of the quotation marks?
- What if you leave out both?
- What if you spell print wrong?
This kind of experiment helps you remember what you read; it also helps when you are programming, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.
- In a print statement, what happens if you leave out one of the parentheses, or both?
- If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
- You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2?
- In math notation, leading zeros are ok, as in 02. What happens if you try this in Python?
- What happens if you have two values with no operator between them?